package com.briup.jd2511.jd2511_product_source.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.briup.jd2511.jd2511_product_source.dao.ManagerFenceHouseMapper;
import com.briup.jd2511.jd2511_product_source.dao.ext.ManagerFenceHouseExtMapper;
import com.briup.jd2511.jd2511_product_source.exception.ServiceException;
import com.briup.jd2511.jd2511_product_source.pojo.ManagerFenceHouse;
import com.briup.jd2511.jd2511_product_source.pojo.ext.ManagerFenceHouseExt;
import com.briup.jd2511.jd2511_product_source.result.Result;
import com.briup.jd2511.jd2511_product_source.result.ResultCode;
import com.briup.jd2511.jd2511_product_source.service.FenceHouseService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;
import java.util.UUID;

@Service
public class FenceHouseServiceImpl implements FenceHouseService {
    @Autowired
    private ManagerFenceHouseMapper managerFenceHouseMapper;
    @Autowired
    private ManagerFenceHouseExtMapper managerFenceHouseExtMapper;

    /**
     * 根据条件分页查询
     *
     * @param fhName   栏舍名称
     * @param pageName 页码
     * @param pageSize 每页数量
     * @return
     */
    @Override
    public PageInfo<ManagerFenceHouse> getAllFhNameByPage(String fhName, Integer pageName, Integer pageSize) throws ServiceException {
        PageHelper.startPage(pageName, pageSize);   // 开启分页
//        String imp = "%" + fhName + "%"; // 在service实现层模糊查询,可以让其他的方法精确匹配
        List<ManagerFenceHouse> list = managerFenceHouseMapper.queryAllHouses(fhName);
        PageInfo<ManagerFenceHouse> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 根据栏舍id查询详情
     *
     * @param fhId 栏舍id
     * @return com.briup.jd2511.jd2511_product_source.pojo.ext.ManagerFenceHouseExt
     * @throws ServiceException
     */
    @Override
    public ManagerFenceHouseExt getDetailByFhId(String fhId) throws ServiceException {
        return managerFenceHouseExtMapper.selectByFhId(fhId);
    }

    /**
     * 保存或者更新
     *
     * @param house 栏舍信息对象
     *              注意：如果id存在则为修改，不存在则为新增
     */
    @Override
    public Result saveOrUpdate(ManagerFenceHouse house) throws ServiceException{
        //栏舍名称必须存在
        if(!StringUtils.hasText(house.getFhName())){
            return Result.failure(ResultCode.PARAM_IS_EMPTY);
        }
        // 判断id是否为空来判断是新增还是修改,如果id为空，则使用UUID自动生成随机序列
        String fhId = house.getFhId();
        if(StringUtils.hasText(fhId)){// id不为空
            // 修改
            // a.根据fhId查询 栏舍是否存在
            ManagerFenceHouse fenceHouse = managerFenceHouseMapper.selectByFhId(fhId);
            if(fenceHouse == null){// id对应的栏舍不存在
                return Result.failure(ResultCode.DATA_IS_EMPTY);
            }
            // b.判断fhName是否有效[唯一 或 原值]
            String fhName = house.getFhName();
            if(fhName.equals(fenceHouse.getFhName())){
                // 原值，不需要判断是否重复，直接更新
            }else{
                // 不同，判断是否重复
                fenceHouse = managerFenceHouseMapper.selectByFhName(fhName);
                if(fenceHouse != null){
                    // 栏舍名称重复
                    return Result.failure(ResultCode.FENCE_HOUSE_IS_EXIST);
                }
                // 不重复，更新
            }
            // c.更新操作
            managerFenceHouseMapper.updateFenceHouse(house);
            return Result.success();
        }else {
            // 新增
            // a.判断fhName是否重复
            ManagerFenceHouse fenceHouse = managerFenceHouseMapper.selectByFhName(house.getFhName());
            if(fenceHouse != null){
                // 栏舍名称重复
                return Result.failure(ResultCode.FENCE_HOUSE_IS_EXIST);
            }
            // b.生成id
            UUID uuid = UUID.randomUUID();
            String finallyId = uuid.toString().replace("-","");// 去掉-
            house.setFhId(finallyId);
            // 新增操作
            managerFenceHouseMapper.insertFenceHouse(house);
            return Result.success();
        }


     /*
        String fhId = house.getFhId();
        String fhName = house.getFhName();
        if(StringUtils.hasText(fhId)){
            throw new ServiceException(ResultCode.FENCE_HOUSE_IS_EXIST;
        }
        List<ManagerFenceHouse> list = managerFenceHouseMapper.queryAllHouses(fhName);
        if(CollUtil.isNotEmpty(list)){
            throw new ServiceException(ResultCode.FENCE_HOUSE_IS_EXIST);
        }
        if (StrUtil.isBlank(fhId)){
            house.setFhId(IdUtil.fastSimpleUUID());
            house.insertFenceHouse(house);
        }

      */
    }

    /**
     * 根据id删除
     *
     * @param fhId 栏舍id
     * @return com.briup.jd2511.jd2511_product_source.result.Result
     */
    @Override
    public void deleteById(String fhId) throws ServiceException{
        // 先查询要删除的栏舍下面有没有栏圈
        ManagerFenceHouseExt ext = managerFenceHouseExtMapper.selectByFhId(fhId);
        if(Objects.isNull(ext)){
            throw new ServiceException(ResultCode.DATA_IS_EMPTY);
        }
        if(CollUtil.isNotEmpty(ext.getMhs())){
            throw new ServiceException(ResultCode.DATA_CAN_NOT_DELETE);
        }
        managerFenceHouseMapper.deleteById(fhId);
    }

    /**
     * 批量删除
     *
     * @param fhIds 栏舍id数组
     * @return com.briup.jd2511.jd2511_product_source.result.Result
     */
    @Override
    public void deleteByIdAll(List<String> fhIds) throws ServiceException {
        // 参数校验
        if(CollUtil.isEmpty(fhIds)){
            throw new ServiceException(ResultCode.PARAM_IS_EMPTY);
        }
        // 如果传递所有id全部无效【id对应的栏舍不存在、栏舍下存在栏圈】，则提醒删除失败；只要有1个id删除成功，则返回操作成功！
        // 开始判断有效id，先准备一个list存储有效id，有效id即不为空的，也就是下面的ext不为空
        List<String> validIds = CollUtil.newArrayList();
        fhIds.forEach(id -> {
            ManagerFenceHouseExt ext = managerFenceHouseExtMapper.selectByFhId(id);
            //当ext不为空时，继续判断其实的mhs是否有效
            if (ext != null){ // ext不为空
                if(CollUtil.isEmpty(ext.getMhs())){ // mhs为空，可以删除
                    validIds.add(ext.getFhId());
                }else {
                    throw new ServiceException(ResultCode.DATA_CAN_NOT_DELETE);
                }
            }
        });
        // 判断validIds是否有值，如果没有值，抛出异常
        if(CollUtil.isEmpty(validIds)){
            throw new ServiceException(ResultCode.DATA_IS_EMPTY);
        }else {
            managerFenceHouseMapper.deleteByIdAll(validIds);
        }

    }

    /**
     * 查询所有栏舍信息（单表）
     *
     * @return java.util.List<com.briup.jd2511.jd2511_product_source.pojo.ManagerFenceHouse>
     */
    @Override
    public List<ManagerFenceHouse> queryAll() {
        // 复用之前的条件分页查询接口里的部分方法，即获取所有栏舍信息
        return managerFenceHouseMapper.queryAllHouses( null);
    }


}
